package com.atguigu.tingshu.album.manager;

import com.atguigu.tingshu.album.config.CosConstantProperties;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.*;
import com.qcloud.cos.utils.IOUtils;
import jakarta.annotation.PreDestroy;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@Slf4j
@Component
public class CosManager {

    @Autowired
    private COSClient cosClient;

    @Autowired
    private CosConstantProperties cosConstantProperties;

    @PreDestroy
    public void shutdown() {
        cosClient.shutdown();
    }

    /**
     * 描述：上传文件到腾讯云
     *
     * @param key
     * @param file
     * @return PutObjectResult
     * @author daiyuling
     * @date 2025/10/22
     */
    public String putObject(String key, File file) {
        // 本地文件路径
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosConstantProperties.getBucketName(), key, file);
        // 设置存储类型（如有需要，不需要请忽略此行代码）, 默认是标准(Standard), 低频(standard_ia)
        putObjectRequest.setStorageClass(StorageClass.Standard_IA);
        PutObjectResult putObjectResult = null;
        try {
            putObjectResult = cosClient.putObject(putObjectRequest);
            System.out.println(putObjectResult.getRequestId());
        } catch (Exception e) {
            log.error("上传文件失败", e);
        }
        // 返回文件路径
        return cosConstantProperties.getHost() + key;
    }

    /**
     * 描述：下载文件
     *
     * @param key 文件key
     * @return 下载后的本地文件
     * @author daiyuling
     * @date 2025/10/22
     */
    @SneakyThrows
    public File getObject(String key) {
        // 存储桶的命名格式为 BucketName-APPID，此处填写的存储桶名称必须为此格式
        String bucketName = cosConstantProperties.getBucketName();
        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);

        InputStream cosObjectInput = null;
        COSObject cosObject = null;
        File tempFile = null;
        try {
            cosObject = cosClient.getObject(getObjectRequest);
            cosObjectInput = cosObject.getObjectContent();
            // 创建临时文件
            tempFile = File.createTempFile("download_", ".tmp");
            tempFile.deleteOnExit(); // 程序退出时自动删除
            // 使用 commons-io 或其他工具类将输入流写入文件
            try (FileOutputStream outputStream = new FileOutputStream(tempFile)) {
                IOUtils.copy(cosObjectInput, outputStream);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
            throw e;
        } finally {
            // 关闭输入流
            if (cosObjectInput != null) {
                try {
                    cosObjectInput.close();
                } catch (IOException ignored) {
                }
            }
        }
        return tempFile;
    }
}
